package com.example.demo11.controller;

import com.example.demo11.entity.UserBean;

import com.example.demo11.service.UserService;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;


@Slf4j
@Controller
public class LoginController {
    //将Service注入Web层
    @Resource
    UserService userService;

    @Resource
    DefaultKaptcha captchaProducer;

    //实现登录
    @RequestMapping("/login")
    public String show(){
        return "login";
    }

    @RequestMapping(value = "/loginIn", method = RequestMethod.POST)
    public String login(String username, String password, String captcha, HttpSession session, Model model){
        // 验证码校验
        String code = (String) session.getAttribute("code");
        if (code == null || !code.equals(captcha)) {
            model.addAttribute("error", "验证码错误");
            return "login";
        }

        UserBean userBean = userService.LoginIn(username,password);
        log.info("username:{}", username);
        log.info("password:{}", password);
        if (userBean != null) {
            session.setAttribute("user", userBean); // 保存用户信息到 Session
            model.addAttribute("user", userBean);   // 给 home 页面传值
            return "home"; // 登录成功后跳转到 home.html 页面
        } else {
            model.addAttribute("error", "用户名或密码错误");
            return "login"; // 登录失败回到登录页
        }
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate(); // 清除 session 数据
        return "redirect:/login";
    }



    @GetMapping("/home")
    public String homePage(HttpSession session, Model model) {
        UserBean user = (UserBean) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }
        model.addAttribute("user", user);
        return "home";
    }


    // 生成验证码
    @GetMapping("/captcha")
    public void getCaptcha(HttpServletResponse response, HttpSession session) throws IOException {
        response.setContentType("image/jpeg");
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);

        String capText = captchaProducer.createText();
        session.setAttribute("code", capText);

        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "jpg", out);
        out.flush();
        out.close();
    }



}
